package dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.NoResultException;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;

public abstract class ModelDAO<T> {
	private static final EntityManagerFactory emf = Persistence.createEntityManagerFactory("CentralEstagio");
	private EntityManager em;
	
	private Class<T> entityClass;
	
	public void begin(){
		em = emf.createEntityManager();
		em.getTransaction().begin();
	}
	
	public void commit(){
		em.getTransaction().commit();
		em.close();
	}
	
	public ModelDAO(Class<T> entityClass) {
        this.entityClass = entityClass;
    }
 
    public void save(T entity) {
        em.persist(entity);
    }
 
    public void delete(int id) {
        T a = em.find(entityClass, id);
        em.remove(a);
    }
 
    public void update(T a) {
        em.merge(a);
    }
 
    public T search(int a) {
        return em.find(entityClass, a);
    }
    
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public List<T> findAll() {
        CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
        cq.select(cq.from(entityClass));
        return em.createQuery(cq).getResultList();
    }
    
    @SuppressWarnings("unchecked")
	public T buscarObjeto(String hql, T a){
    	System.out.println(a);
    	try{
    		Query query = em.createQuery(hql);
    		a = (T) query.getSingleResult();
    		return a;
    	}catch(NoResultException e){
    		return null;
    	}
    }
    
	@SuppressWarnings("unchecked")
	public List<T> buscar(String hql){
		Query query = em.createQuery(hql);
    	return query.getResultList();
    }
}
